package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorUserEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.CompetitorUserModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yingjf
 * @date: 2022/9/2 08:58
 * @description: 工作流竞争对手策略
 */
@Service
@Slf4j
public class WorkflowCompetitorStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private CompetitorUserModel competitorUserModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.COMPETITOR.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                CompetitorEntity  competitorEntity = new CompetitorEntity();
                competitorEntity.setId(workflowTransferPOJO.getData().getId());
                competitorEntity.setCorpid(corpid);
                competitorEntity.setData(data);
                competitorEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                competitorEntity.setOwnerId(getOwnerId(data));
                competitorEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    competitorEntity.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                competitorModel.update(competitorEntity);
                // 回退被删掉的子表单
                updateBackSubForm(competitorEntity, corpid, IndexTypeEnum.IDX_SAAS_COMPETITOR_SUB);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCompetitorStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            CompetitorEntity competitorEntity = new CompetitorEntity();
            competitorEntity.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                competitorEntity.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                competitorEntity.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            competitorEntity.setCorpid(corpid);
            competitorEntity.setUpdateTime(DateTimeUtil.getInt());
            competitorModel.update(competitorEntity);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_COMPETITOR_SUB, del);

            // 团队
            Map<String,Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid",corpid);
            params.put("competitorId",corpid);
            params.put("del",0);
            List<CompetitorUserEntity> contractUserList = competitorUserModel.findEntitys(params);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                competitorUserModel.deleteBatch(corpid, contractUserList, WriteRequest.RefreshPolicy.NONE, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCompetitorStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
